package com.cib.process.ngd.impl;

import com.cib.process.bean.NGDQueryResult;
import com.cib.process.bean.NGDStartResult;
import com.cib.process.bean.QueryRequestParam;
import com.cib.process.ngd.NGDService;
import com.cib.process.util.GsonUtil;
import com.cib.process.util.LoggerHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sun.org.apache.bcel.internal.generic.NEW;
import io.netty.handler.codec.Headers;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;


public class NGDServiceImpl implements NGDService {
    //ngd相关配置
    private String startUrl;
    private String queryUrl;
    private String startType;
    private String startChannel;
    private String queryChannel;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public NGDStartResult start(String sessionId, String userId, String token, String channel) {
        ResponseEntity<String> responseEntity=null;
        long startTime = System.currentTimeMillis();
        try {
            MultiValueMap<String,String> params=new LinkedMultiValueMap<>();
            if (StringUtils.isNotBlank(sessionId)){
                params.add("sessionId",sessionId);
            }
            params.add("channel",StringUtils.isNotBlank(channel)?channel:startChannel);
            params.add("type",startType);
            String extStr="{\"phone\"}:\""+userId+"\"}";
            params.add("ext",extStr);

            //封装请求对象
            HttpEntity<MultiValueMap> httpEntity = new HttpEntity<>(params, getHeaders(token, MediaType.APPLICATION_JSON_UTF8));
            LoggerHelper.info(this.getClass(),"[sessionId:{}] [userId:{}] start invoke params:{}",sessionId,userId,params);
            responseEntity=restTemplate.exchange(startUrl, HttpMethod.POST,httpEntity,String.class);
            LoggerHelper.info(this.getClass(),"start接口调用的结果为：{}",responseEntity.getBody());
            NGDStartResult result = GsonUtil.GSON.fromJson(responseEntity.getBody(), new TypeToken<NGDStartResult>() {
            }.getType());

            return result;
        }catch (Exception e){
            LoggerHelper.err(this.getClass(),"[sessionId:{}] [userId:{}] start invoker failed",sessionId,userId,e);
        }finally {
            long endtime=System.currentTimeMillis();
            LoggerHelper.info(this.getClass(),"[sessionId:{}] [userId:{}] start invoke time{}ms",sessionId,userId,endtime-startTime);
        }
        return null;
    }

    /**
     *
     * @param sessionId
     * @param userId
     * @param token
     * @param channel
     * @param flag
     * @return
     */
    public NGDStartResult start(String sessionId, String userId, String token, String channel,int flag){
        ResponseEntity<String> responseEntity=null;
        NGDQueryResult queryResult=null;
        QueryRequestParam queryRequestParam = new QueryRequestParam();

        //因为是query接口请求的，为了适配原有代码，封装一个start返回对象
        NGDStartResult result=new NGDStartResult();
        long startTime=System.currentTimeMillis();
        try {
            if (StringUtils.isNotBlank(sessionId)){
              queryRequestParam.setSessionId(sessionId);
            }
            queryRequestParam.setChannel(channel);
            //传一个欢迎语意图可以识别的固定话术
            queryRequestParam.setQueryText("欢迎语意图文本");
            //第一次接入，能够得到的只有手机号
            Map<String,Object> context=new HashMap<>();
            context.put("userId",userId);
            queryRequestParam.setContext(context);


            String json = GsonUtil.GSON.toJson(queryRequestParam);
            LoggerHelper.info(this.getClass(),"[sessionId:{}] [userId:{}] start invoke params:{}",sessionId,userId,json);
            HttpEntity<String> httpEntity=new HttpEntity<>(json,getHeaders(token,MediaType.APPLICATION_JSON_UTF8));
            responseEntity=restTemplate.postForEntity(queryUrl,httpEntity,String.class);
            queryResult=GsonUtil.GSON.fromJson((String) responseEntity.getBody(),
                    new TypeToken<NGDQueryResult>(){
                    }.getType());
            LoggerHelper.info(this.getClass(),"start接口调用的结果为：{}",responseEntity.getBody());
            //返回话术即为欢迎语
            String suggestAnswer = queryResult.getData().getSuggestAnswer();

            result.setMsg(queryResult.getMsg());//错误信息
            result.getData().setWelcome(suggestAnswer);//欢迎语
            result.getData().setSessionId(queryResult.getData().getSessionId());
            result.setCode(queryResult.getCode());//响应码
            return result;

        }catch (Exception e){
            LoggerHelper.err(this.getClass(),"[sessionId:{}] [userId:{}] start invoker failed",sessionId,userId,e);
        }finally {
            long endtime=System.currentTimeMillis();
            LoggerHelper.info(this.getClass(),"[sessionId:{}] [userId:{}] start invoke time{}ms",sessionId,userId,endtime-startTime);
        }
        return null;
    }

    @Override
    public NGDQueryResult query(QueryRequestParam queryRequestParam, String userId, String token, String channel) {
        ResponseEntity responseEntity=null;
        NGDQueryResult queryResult=null;
        long startTime=System.currentTimeMillis();

        try {
            queryRequestParam.setChannel(StringUtils.isNotBlank(channel)?channel:queryChannel);
            String json = GsonUtil.GSON.toJson(queryRequestParam);
            LoggerHelper.info(this.getClass(),"[sessionId:{}] [userId:{}] ndg query params {}",queryRequestParam.getSessionId(),userId,json);
            HttpEntity<String> httpEntity=new HttpEntity<>(json,getHeaders(token,MediaType.APPLICATION_JSON_UTF8));
            responseEntity=restTemplate.postForEntity(queryUrl,httpEntity,String.class);
            queryResult=GsonUtil.GSON.fromJson((String) responseEntity.getBody(),
                    new TypeToken<NGDQueryResult>(){

                    }.getType());
            return queryResult;
        }catch (Exception e){
            LoggerHelper.err(this.getClass(),"[sessionId:{}] [userId:{}] [responseEntity:{}] query invoke failed {}",queryRequestParam.getSessionId(),userId,responseEntity,e);
        }finally {
            long endTime=System.currentTimeMillis();
            LoggerHelper.info(this.getClass(),"[sessionId:{}] [userId:{}] query invoke time {}ms",queryRequestParam.getSessionId(),userId,endTime-startTime);
        }
        return null;
    }

    private HttpHeaders getHeaders(String token, MediaType mediaType) {

        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization","NGD"+token);
        if (mediaType!=null){
            headers.setContentType(mediaType);
        }
        return headers;

    }


}
